/*TODO

indent
   - make flexable to accomidate any width
   - make it count characters not bytes (utf8 support)
*/

#include <stdlib.h>
#include <string.h>

#include "mcl/mcl.h"
#include "mcl/formatter.h"

mcl_formatter_c mcl_formatter___nomemory;

mcl_formatter_c* mcl_formatter_init(){
   mcl_formatter_c *context;
   
   if(!(context=(mcl_formatter_c *) malloc(sizeof(mcl_formatter_c)))){
      mcl_formatter___nomemory.status=MCL_STATUS_EMEM;
      return &mcl_formatter___nomemory;
   }
   *context=mcl_formatter___nomemory;
   
   mcl_formatter___nomemory.status=MCL_STATUS_OK;
   context->width=80;
   return context;
}

char *mcl_formatter_indent(mcl_formatter_c* c,
                           char *what,
                           int spaces){
   int i=0, j, flag=0; char ch;
   int slen=strlen(what);
   int sublen=c->width-spaces;
   int overall = (slen/sublen+1)*(spaces+1)+slen+1; // last one is for nul
   //                         ^ if what doesn't span more than one line (cant have zero)
   //                                    ^ is for the new line char (if needed)
   
   #include <stdio.h> 
   printf("what size: %d\nrequested size: %d\n", slen, sublen);
   if(!(c->buf=(char *)realloc(c->buf, sizeof(char)*(overall)))){
		return NULL;
	}
   
   while(1){
      printf("%d ", i);
      for (j=0;j<spaces;++j) c->buf[i++]=' ';
      for (j=0;j<sublen;++j){ 
         if(!(ch=*(what++))){ flag=1; break;}
         c->buf[i++]=ch;
      }
      c->buf[i++]='\n';
      if (flag) break;
   }
   return c->buf;
}

mcl_formatter_c* mcl_formatter_fin(mcl_formatter_c *c){
   if (c){
      if(c->buf) free(c->buf);
      free(c);
   }
   return NULL;
}

